package tako.wisers.com.android.apis.handler;

import java.util.List;

import android.widget.AutoCompleteTextView;
import android.widget.Toast;
import tako.wisers.com.android.apis.R;
import tako.wisers.com.android.apis.activity.Tako;
import tako.wisers.com.android.apis.adapter.ListManager;
import tako.wisers.com.android.apis.event.Event;
import tako.wisers.com.android.apis.event.EventBus;
import tako.wisers.com.android.apis.item.NewsItem;
import tako.wisers.com.android.apis.location.GPSManager;
import tako.wisers.com.android.apis.parser.NewsHeadlineParser;
import tako.wisers.com.android.apis.util.Global;

public class NewsHandler extends TakoHandler {
	public NewsHandler(Tako tako) {
		super(tako);
	}

	private String keyword;

	@Override
	public void execute(Event event) {
		if (tako.getBottomDisplay() != Global.LIST_DISPLAY) {
			Event lEvent = new Event(R.id.list, Event.EVENT_SWITCH, false);
			EventBus.getInstance().executeEvent(lEvent);
		}
		AutoCompleteTextView editorText = (AutoCompleteTextView) tako
				.findViewById(R.id.keyword);
		keyword = editorText.getText().toString();
		String countryCode = null;
		if (editorText.getVisibility() != AutoCompleteTextView.VISIBLE
				|| keyword == null || keyword.equals("")) {
			GPSManager mlocationListener = GPSManager.getInstance();
			mlocationListener.setLocation(mlocationListener.getMapView()
					.getMapCenter());
			keyword = mlocationListener.getLocationName();
			countryCode = mlocationListener.getCountryCode();
		}
		List<NewsItem> items = new NewsHeadlineParser().getNewsHeadlines(
				keyword, countryCode);
		if (items == null || items.size() == 0) {
			mhandler.sendMessage(mhandler.obtainMessage(SEARCH_FASILER));
		} else {
			ListManager.getInstance(tako).loadNews(items);
			mhandler.sendMessage(mhandler.obtainMessage(SEARCH_SUCCESS));
		}
		System.gc();
	}

	private android.os.Handler mhandler = new android.os.Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			AutoCompleteTextView editorText = (AutoCompleteTextView) tako
					.findViewById(R.id.keyword);
			editorText.setText(keyword);
			tako.dismissDialog();
			if (msg.what == SEARCH_FASILER)
				tako.dialogShow(Global.WAITING_DIALOG);
		}
	};

}
